package Login;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.*;
import java.io.IOException;

@WebFilter(
        filterName = "LoginFilter",
        urlPatterns = "/*"
)
public class LoginFilter implements Filter {
    private static final String[] EXCLUDE_URLS = {
            "/login",
            "/Login-community",
            "/static/",
            "/"
    };

    private String loginPage = "/WEB-INF/Login/Login.jsp";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String contextPath = httpRequest.getContextPath();
        String requestURI = httpRequest.getRequestURI();
        String url = requestURI.substring(contextPath.length());

        System.out.println("not: " + url);


        if (isExcludeUrl(url)) {
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            System.out.println("notLogin");

            request.setAttribute("error", "Login");
            request.getRequestDispatcher(loginPage).forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    private boolean isExcludeUrl(String url) {
        for (String excludeUrl : EXCLUDE_URLS) {
            if (url.startsWith(excludeUrl)) {
                return true;
            }
        }
        return false;
    }
    }
